<template>
  <el-dialog
    title="物料存储管理导入"
    :visible.sync="visible"
    width="555px"
    append-to-body
    @open="importConfigOpen"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <avue-form ref="importConfigForm" v-model="importForm" :option="importConfig.option">
      <template slot="imgUrl">
        <el-upload
          ref="excelFile"
          class="importConfigDialog"
          drag
          action="#"
          :accept="accept"
          limit="1"
          :auto-upload="false"
          :before-remove="handleBeforeRemove"
          :on-change="changeFile"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">
            <div>请上传{{ accept }}标准格式文件</div>
          </div>
        </el-upload>
      </template>
      <template slot="excelTemplate">
        <el-button type="primary" @click="handleDownLoad()" icon="el-icon-download el-icon--right"> 模板下载 </el-button>
      </template>
    </avue-form>
    <div slot="footer" class="dialog-footer">
      <el-button v-preventReClick type="primary" size="small" @click="saveImport" icon="el-icon-circle-plus-outline">保 存 </el-button>
      <el-button @click="cancelImport" size="small" icon="el-icon-circle-close">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getToken } from '@/util/auth';
import request from '@/router/axios';
import { getExprot } from '@/api/warehouse/materialStorageManagement';

export default {
  name: 'materialStorageImport',
  inject: ['globalStartLoad', 'globalEndLoad'],
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    accept: {
      type: String,
      default: '.xls,.xlsx'
    },
    id: {
      type: String,
      default: ''
    },
    inventoryId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      importForm: {
        imgUrl: {}
      },
      importConfig: {
        fileLoading: false,
        fileLoadingText: '文件下载中，请稍后...',
        option: {
          emptyBtn: false,
          submitBtn: false,
          column: [
            {
              label: '附件上传',
              prop: 'imgUrl',
              type: 'upload',
              loadText: '文件上传中，请稍等',
              span: 24,
              propsHttp: {
                res: 'data'
              },
              data: {},
              headers: {
                'Blade-Auth': getToken()
              },
              tip: '只能上传拓展名为.xls,.xlsx的文件',
              action: '#'
            },
            {
              label: '模板下载',
              prop: 'excelTemplate',
              formslot: true,
              span: 24
            }
          ]
        }
      }
    };
  },
  methods: {
    importConfigOpen() {
      for (const key in this.importForm) {
        this.importForm.imgUrl = {};
      }
      this.$nextTick(() => {
        this.$refs.excelFile.clearFiles();
      });
    },
    handleClose() {
      this.setVisible(false);
    },
    saveImport() {
      if (Object.keys(this.importForm.imgUrl).length == 0) {
        this.$message.warning('请先上传文件后再操作！');
        return;
      }
      const file = this.importForm.imgUrl;
      let fileParams = new FormData();
      fileParams.append('file', file);
      this.globalStartLoad('导入数据中，请稍后...', 'rgba(255,255,255,0.9)');
      request({
        url: `/api/mes-admin/area/import-part-storage-setting?inventoryMaterialStorageLevel=${this.id}&inventoryId=${this.inventoryId}`,
        method: 'post',
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        data: fileParams
      })
        .then((res) => {
          this.$message.success(res.data.msg);
          this.$emit('submit', true);
          this.setVisible(false);
          this.$refs.importConfigForm.resetFields();
        })
        .catch((err) => {
          this.$refs.excelFile.clearFiles();
          this.importForm.imgUrl = {};
        })
        .finally(() => {
          this.globalEndLoad();
        });
    },
    async handleBeforeRemove(file, fileList) {
      let res = await this.$confirm(`确定移除 ${file.name}？`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      });
      if (res) {
        this.importForm.imgUrl = {};
        this.$message({
          type: 'success',
          message: '移除成功!'
        });
      }
    },
    changeFile(val) {
      let nameArray = val.name.split('.');
      if (nameArray[nameArray.length - 1] === 'xlsx' || nameArray[nameArray.length - 1] === 'xls') {
        // file保存选择的文件
        this.importForm.imgUrl = val.raw;
      } else {
        this.$message({
          message: '文件格式错误,请确认文件内容并重新上传',
          type: 'warning',
          duration: 2000
        });
      }
    },
    cancelImport() {
      this.setVisible(false);
    },
    setVisible(val) {
      this.$emit('update:visible', val);
    },
    async handleDownLoad() {
      let res;
      try {
        res = await getExprot();
      } catch (e) {
        console.warn(e);
      }
      const blob = new Blob([res.data]);
      const fileName = '物料存储管理导入.xlsx';
      const link = document.createElement('a');
      link.download = fileName;
      link.style.display = 'none';
      link.href = URL.createObjectURL(blob);
      document.body.append(link);
      link.click();
      URL.revokeObjectURL(link.href);
      document.body.removeChild(link);
    }
  }
};
</script>

<style scoped lang="scss">
.importConfigDialog .el-upload {
  width: 100%;
}

.importConfigDialog .el-upload-dragger {
  width: 100%;
}

.custom-upload {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.model-download {
  cursor: pointer;

  .icon-color {
    color: #409eff;
    margin-right: 4px;
    font-size: 16px;
  }

  :hover {
    color: #409eff;
  }
}
</style>
